package cn.tedu.knows.portal.service.impl;

import cn.tedu.knows.portal.mapper.UserMapper;
import cn.tedu.knows.portal.model.Permission;
import cn.tedu.knows.portal.model.Role;
import cn.tedu.knows.portal.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=mapper.findUserByUsername(username);
        if (user==null){
            return null;
        }
        List<Permission> permissions=mapper.findUserPermissionsById(user.getId());

         String [] auth=new String[permissions.size()];
         int i=0;
         for (Permission p :permissions){
             auth[i]=p.getName();
             i++;
         }
         List<Role>roles=mapper.findUserRolesById(user.getId());
         auth= Arrays.copyOf(auth,auth.length+roles.size());
         for (Role role:roles){
             auth[i]=role.getName();
             i++;
         }

         UserDetails details = org.springframework.security.core.userdetails.User.builder()
                 .username(user.getUsername())
                 .password(user.getPassword())
                 .authorities(auth)
                 .accountLocked(user.getLocked()==1)
                 .disabled(user.getEnabled()==0)
                 .build();
        return details;
    }
}
